import React, {Component} from "react";
import PropTypes from 'prop-types';
import AcGird from "./Grid";
//import AcGird from "components/Grid";
import RenderColumn from './RenderColumn';
import isequal from 'lodash.isequal';
import cloneDeep from 'lodash.clonedeep';
import ReactDOM from 'react-dom'
import Icon from 'bee-icon';
import ButtonGroup from 'bee-button-group';
import Tooltip from 'bee-tooltip';
import Btns from 'ac-btns';
import {initValueString,ts2Formatter,toThousands} from 'utils';


const propTypes = {
    onChange:PropTypes.func,//数据改变回调
    clsfix:PropTypes.string,
    onOpenChange:PropTypes.func,//展开收起回调
    title:PropTypes.string,
    disabled:PropTypes.bool,//是否可编辑
    state:PropTypes.string,//是否可编辑
    onDel:PropTypes.func,//删除的回调
    defaultOpen:PropTypes.bool,//默认是否打开
    showIndex:PropTypes.bool,//是否显示序号列
    excludeKeys:PropTypes.array,//粘贴时不需要粘贴的key值合计
}

const defaultProps = {
    title:'标题',
    clsfix:'ac-edit-grid',
    data: [],
    columns:[],
    onChange:()=>{},
    onOpenChange:()=>{},
    onDel:()=>{},
    showIndex:true,
    excludeKeys:[]
};

class EditGrid extends Component {
    constructor(props) {
        super(props);
        this.state={
            columns:props.columns,
            data:props.data||[],
            selectData:[],//选中的数据
            selectDataIds:[],//记录选中数据的id，id在这里生成，componentWillReceiveProps更新data时，设置选中的数据
            copying:false,//是否正在拷贝
            open:props.defaultOpen||true,//默认展开收起
            isMax:false,//是否最大化了
            defaultValueKeyValue:{},//带默认值的key，value键值对
        }
        this.selectDataId = 1;
    }

    componentWillMount(){
        let {columns,status,btnPageFlag} = this.props;
        columns = this.hideColumn(columns,btnPageFlag);
        this.setDataColumn(this.props.disabled,columns,this.state.data,status,btnPageFlag);
    }

    setDataColumn=(disabled,col,da,status,btnPageFlag="1")=>{
        let {onValidate} = this.props;
        let columns = cloneDeep(col);
        let defaultValueKeyValue = {};
        // if(this.props.showIndex){
        //     columns.unshift({
        //         title: "序号",
        //         dataIndex: "index",
        //         key: "index",
        //         fixed:"left",
        //         width: 70,
        //         render:(text,record,index)=>{
        //             return index+1;
        //         }
        //       })
        // }
        columns.forEach(item => {
            item.oldRender = item.render;
            let showtitle = item.title;
            if(btnPageFlag == "2" || !item.renderType) {
                item.width = item.detailwidth || 100;
                item.render=(text,record,index)=>{
                    let placement = 'left';
                    if(typeof text =="number" && text===0) text="0";
                    let value = text || item.defaultValue || "";
                    value = this.getValue(value,item,record,index);
                    if(item.textAlign)placement=item.textAlign=='center'?'bottom':item.textAlign;
                    return <Tooltip overlay={value} inverse placement={placement}>
                                <span className='ac-grid-cell'>{value}</span>
                            </Tooltip>
                }
            }else{
                if(!disabled){
                    if(item.required){
                        item.title=<span className={`${this.props.clsfix}-column-title-required`}>{item.title}</span>
                    }
                }
                if(btnPageFlag != "0" && item.filedProps) {
                    delete item.filedProps.defaultValue;
                }

                if(item.filedProps&&(item.filedProps.defaultValue!=undefined))defaultValueKeyValue[item.dataIndex]=item.filedProps.defaultValue;
                item.render=(text,record,index)=>{
                    
                    return <RenderColumn
                                valueField={item.valueField}
                                config={item.config}
                                textAlign={item.textAlign}
                                renderType={item.renderType}
                                index={index}
                                title={showtitle}
                                dataIndex={item.dataIndex}
                                value={text}
                                record={record}
                                status={status}
                                btnPageFlag={btnPageFlag}
                                //initialValue={item.filedProps && item.filedProps.reffields && initValueString(record[item.filedProps.reffields.refname], record[item.filedProps.reffields.refpk], item.required,record[item.filedProps.reffields.refcode])}
                                options={item.options}
                                onChange={this.onChange}
                                validate={item.validate} 
                                required={item.required}
                                pattern={item.pattern}
                                patternMessage={item.patternMessage}
                                disabled={disabled?true:item.disabled}
                                customizeRender={item.customizeRender}
                                itemProps = {item}
                                onValidate = {onValidate}
                                // cRefType={item.cRefType}
                                // displayname={item.displayname}
                                // iconStyle={item.iconStyle}
                                // max={item.max}
                                // min={item.min}
                                // step={item.step} 
                                // precision={item.precision}
                                // maxLength={item.maxLength}
                                filedProps={item.filedProps}
                            />
                }
            }
        });
        this.setState({
            columns,
            defaultValueKeyValue
        })
        //给data加index
        let data  = cloneDeep(da);
        if(data[0]&&data[0].index==1){
        }else{
            data.forEach((item,index)=>{
                item.index=index+1
            })
            this.setState({
                data
            })
        }
    }

    /**
     * 千分符
     * @param {要转换的数据} num 
     */
    // toThousands(value){
    //     if(value == 0) return value;
    //     var reg=String(value).indexOf('.') >-1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;//千分符的正则
    //     let StringValue = String(value).replace(reg, '$1,')
    //     return StringValue;
    // }

    getValue=(value,item,record,index)=>{
        let { renderType } = item;
        if(typeof item.oldRender =='function') {
            return item.oldRender(value,record,index)
        }

        if(renderType&&(renderType=='select' || renderType=='selectradio')){
            item.filedProps.options && item.filedProps.options.forEach(item => {
                if(item.code===value){
                    value = item.name
                }
            });
        }else if(renderType&&(renderType=='inputnumber') && (value || value===0)){
            value = toThousands(value,item.filedProps && item.filedProps.precision);
        }else if(renderType&&(renderType=='datepicker') && value) {
            value = ts2Formatter(value);
        }
        return value;
    }

    offerSetField = (data,index,itemProps,value,dataObj) => {
        let {offersparam} = itemProps.filedProps;
        if(itemProps.renderType == "refcomponent" && offersparam) {
            let field;
            offersparam.currentkey.map((item,i)=>{
                field = offersparam.offerfields[i];
                data[index][field] = dataObj[item] || "";
            })
        }
        return data;
    }

    resetField = (data,index,itemProps,value,dataObj) =>{
        let {reffields} = itemProps.filedProps;
        if(itemProps.renderType == "refcomponent" || itemProps.renderType == "select") {
            data[index][reffields.refpk] = dataObj.refpk;
            data[index][reffields.refname] = dataObj.refname;
            data[index][reffields.refcode] = dataObj.refcode;
        }
        if(itemProps.renderType == "selectradio") {
            data[index][reffields.refpk] = dataObj.refcode;
        }
        return data;
    }

    resetColumnShow = (value,itemProps) =>{
        let {showparam} = itemProps.filedProps;
        let {columns} = this.state;

        showparam && showparam.map((item,index)=>{
            let matchParams = item.currentkey;

            Object.keys(matchParams).forEach(function (p) {
               if(value == matchParams[p]) {
                    columns.hideField = false;
               }
            })
        })
        this.setState(columns);
    }

    resetColumnRequire = (value,itemProps) =>{
        let {requireparam} = itemProps.filedProps;
        let {columns} = this.state;

        requireparam && requireparam.map((item,index)=>{
            let matchParams = item.currentkey;

            Object.keys(matchParams).forEach(function (p) {
                if(itemProps.renderType == "refcomponent" && value[0][p] == matchParams[p]){
                    columns.required = true;
                }else if(itemProps.renderType == "select" && value[p] == matchParams[p]){
                    columns.required = true;
                }else if(value == matchParams[p]) {
                    columns.required = true;
                }
            })
        })
        this.setState(columns);
    }

    dealMultipleData = (key,index,itemProps,dataObj,data) => {
        let {reffields,offersparam} = itemProps.filedProps;
        if(itemProps.renderType != "refcomponent") return data;

        data[index][reffields.refpk] = dataObj[0].refpk;
        data[index][reffields.refname] = dataObj[0].refname;
        data[index][reffields.refcode] = dataObj[0].refcode;

        if(offersparam) {
            let field;
            offersparam.currentkey.map((item,i)=>{
                field = offersparam.offerfields[i];
                console.log(field,data[index][field],dataObj[0][item]);
                data[index][field] = dataObj[0][item] || "";
            })
        }
        //参照多选时，只会在末行新增
        let flagKey = data.length;
        let newData = {};
        dataObj.map((item,i) => {
            if(i != 0) {
                newData = {
                    [reffields.refname]:item.refname,
                    [reffields.refcode]:item.refcode,
                    [reffields.refpk]:item.refpk,
                    index:flagKey+1,
                    key:flagKey+1,
                    persistStatus:"new"
                }
                flagKey = flagKey+1;
                if(offersparam) {
                    let field;
                    offersparam.currentkey.map((offersitem,i)=>{
                        field = offersparam.offerfields[i];
                        newData[field] = item[offersitem] || "";
                    })
                }
                data.push(newData)
            }

        })
        return data;
    }

    onChange=( value,key,index,itemProps,dataObj)=>{
        //改变data
        let {childType} = this.props;
        let data  = cloneDeep(this.state.data);
        data.map((item,i)=> {
            if(item.index == index) {
                if(item.persistStatus != "new" && item.persistStatus != "fdel" && item[key] != value) {
                    item.persistStatus = "upd";
                }
                item[key]=value;
                index = i;
            }
        })
        
        if(dataObj && (dataObj instanceof Array)) {
            data = this.dealMultipleData(key,index,itemProps,dataObj,data);
        }

        
        if(itemProps.filedProps && dataObj && !(dataObj instanceof Array)) {
            data = this.resetField(data,index,itemProps,value,dataObj);
        }

        if(itemProps &&  itemProps.filedProps && itemProps.filedProps.offersparam && dataObj && !(dataObj instanceof Array)){
            data = this.offerSetField(data,index,itemProps,value,dataObj);
        }
        //this.resetColumn(value,itemProps);
        //this.resetColumnRequire(value,itemProps);
        this.setState({
            data:data
        })
        let operObj = {
            operData:data[index],
            index:index,
            key:key,
            operType:"edit",
            field:key,
            fieldValue:value
        }
        this.props.onChange(data,childType,operObj);
    }

    //选中数据的回调
    getSelectedDataFunc=(selectData)=>{
        let data = this.resetChecked(this.state.data)
        let selectDataIds = []
        selectData.forEach((item)=>{
            data[item.index-1]._checked=!data[item.index-1]._checked;
            let id = 'selectDataId'+this.selectDataId;
            data.selectDataId = id;
            selectDataIds.push(id);
            this.selectDataId++;
        })
        this.setState({
            selectDataIds,
            selectData,
            data
        })
        let operObj = {
            operData:selectData,
            index:null,
            key:null,
            operType:"select"
        }

        this.props.getSelectedDataFunc && this.props.getSelectedDataFunc(selectData,data);
    }

    resetChecked=(dataValue)=>{
        let data = cloneDeep(dataValue);
        data.forEach((item,index)=>{
            item._checked=false
            item.index=index+1,
            item.key=index+1+''
        })
        return data
    }


    componentWillReceiveProps(nextProps){
        if(!isequal(nextProps.data,this.state.data) || this.props.btnPageFlag != nextProps.btnPageFlag){
            let selectDataIds = this.state.selectDataIds;
            nextProps.data.forEach((item,index)=>{
                item.index=index+1;
                if(selectDataIds.indexOf(item.selectDataId)!=-1)item._checked=true;
            })
            this.setState({
                data:nextProps.data,
                btnPageFlag:nextProps.btnPageFlag
            })
        }
        let {columns} = nextProps;
        columns = this.hideColumn(columns,nextProps.btnPageFlag);

        if('disabled' in nextProps){
            this.setDataColumn(nextProps.disabled,columns,nextProps.data,nextProps.status,nextProps.btnPageFlag)
        }
    }

    hideColumn = (columns,btnPageFlag) =>{
        let tempcolumns = cloneDeep(columns);
        if(tempcolumns) {
            tempcolumns = tempcolumns.filter(function(item) {
                if(item.hidepage && item.hidepage[btnPageFlag]) item.hideField=true;
                return !item.hideField;
            });
        }
        return tempcolumns;
    }

    //打开关闭
    open=()=>{
        this.props.onOpenChange(!this.state.open)
        this.setState({
            open:!this.state.open
        })
    }

    addRow=()=> {
        let {beforeAddRow,childType,btnPageFlag} = this.props;
        if(beforeAddRow) {
            beforeAddRow(childType,(defaultValueObj)=>{
                this.afterAddRow(defaultValueObj && defaultValueObj[childType]);
            },btnPageFlag
            )
        }else {
            this.afterAddRow();
        }
        
    }

    //增行
    afterAddRow=(defaultValueObjParam)=>{
        let {defaultValueObj} = this.props;
        let defaultValueKeyValue = this.state.defaultValueKeyValue;
        let data = cloneDeep(this.state.data);
        let length = data.length;
        
        
        let obj = cloneDeep(data[0]||{index:0});
        for(let attr in obj){
            if(attr=='index'){
                obj.index=length+1;
            }else if(attr=='key'){
                obj.key=`${length+1}`;
            }else if(obj[attr]){
                obj[attr] = "";
            }
        }
        if(defaultValueObjParam) {
            defaultValueObjParam.index=length+1;
            defaultValueObjParam.key=length+1;
        }
        if(defaultValueObjParam || defaultValueObj) {
            obj = Object.assign({}, obj, defaultValueObjParam || defaultValueObj);
        }
        for(let attr in defaultValueKeyValue ){
            obj[attr]=defaultValueKeyValue[attr];
        }
        obj.persistStatus = "new";
        delete obj.id;
        data.push(obj)

        let operObj = {
            operData:obj,
            index:null,
            key:null,
            operType:"add"
        }
        this.props.onChange(data,this.props.childType,operObj);
        this.setState({
            data
        })
    }

    extendToEnd = () =>{
        let {openCreateLabel,childType} = this.props;
        if(childType!="activityPlanDetails"){
            return;
        }
        if(openCreateLabel){
            openCreateLabel(this.state);
            //清除选择数据
            this.setState({
                selectData:[]
            })
        }else{
            let {selectData} = this.state;
            let data = cloneDeep(this.state.data)
            let index = selectData[0].index;
            if(!data[index-1].customerId&&!data[index-1].channelTypeId){
                return;
            }
            let customerId = data[index-1].customerId;
            let customerCode = data[index-1].customerCode;
            let customerName = data[index-1].customerName;
            let channelTypeId = data[index-1].channelTypeId;
            let channelTypeCode = data[index-1].channelTypeCode;
            let channelTypeName = data[index-1].channelTypeName;
            data.map(dataItem => {
                if(dataItem.index > index && dataItem.persistStatus != "fdel") {
                    dataItem.customerId = customerId;
                    dataItem.customerCode = customerCode;
                    dataItem.customerName = customerName;
                    dataItem.channelTypeId = channelTypeId;
                    dataItem.channelTypeCode = channelTypeCode;
                    dataItem.channelTypeName = channelTypeName;
                }
            })
            this.setState({
                data,
                selectData:[]
            })
            let operObj = {
                operData:data[index-1],
                index:index-1,
                key:null,
                operType:"edit",
            }
            this.props.onChange(data,childType,operObj);
        }
    }

    copyToAssign = () =>{
        let {openCreateCopyLabel,childType} = this.props;
        if(childType!="activityPlanDetails"){
            return;
        }
        if(openCreateCopyLabel){
            openCreateCopyLabel(this.state);
        }else{
            let copyData = [];
            let data = cloneDeep(this.state.data);
            data.forEach(item=>{
                delete item.id;
                item.persistStatus = "new";
                if(item._checked)copyData.push(item)
            })
            this.setState({
                copying:true,
                selectData:copyData
            })
        }
    }

    //删行
    delRow=()=>{
        let {childType} = this.props;
        let {selectData} = this.state;
        let data = cloneDeep(this.state.data)
        data.map(dataItem => {
            selectData.map((item)=>{
                if(dataItem.index == item.index && dataItem.persistStatus != "fdel") {
                    if(dataItem.persistStatus == "new") {
                        dataItem.persistStatus = null;
                    }else {
                        dataItem.persistStatus = "fdel";
                    }
                }
            })
        })
        console.log("删除",data);
        data = data.filter(function(item) {
            return item.persistStatus !== null
        });
        if (childType=="activityPlanDetails"||childType=="activityDesignDetails") {
            var index = 1;
            data.forEach((item)=>{
                if(item.persistStatus!=="fdel"){
                    item.ext01 = index;
                    index++;
                }
            });
        }
        data = this.resetChecked(data)
        this.setState({
            data,
            selectData:[]
        })

        let operObj = {
            operData:selectData,
            index:null,
            key:null,
            operType:"del"
        }
        sessionStorage.removeItem("errorFields");
        this.props.onChange(data,this.props.childType,operObj);
        this.props.onDel(selectData,childType)
    }
    //复制行
    copyRow=()=>{
        let copyData = [];
        let data = cloneDeep(this.state.data);
        data.forEach(item=>{
            delete item.id;
            item.persistStatus = "new";
            if(item._checked)copyData.push(item)
        })
        this.setState({
            copying:true,
            selectData:copyData
        })
    }
    //粘贴至末行
    copyToEnd=()=>{
        let {copyToEnd,copyStatus,childType} = this.props;
        if(copyStatus){
            copyToEnd();
        }else{
            let {selectData,data} = this.state;
            var rowNum = 1;
            if (childType=="activityPlanDetails"||childType=="activityDesignDetails") {
                data.forEach((item)=>{
                    if(item.persistStatus!=="fdel"){
                        rowNum++;
                    }
                });
            }
            selectData.forEach((item,index)=>{
                item.index = data.length+index+1;
                item.key = data.length+index+1+'';
                if (childType=="activityPlanDetails"||childType=="activityDesignDetails") {
                    item.ext01 = rowNum;
                    rowNum++;
                }
                item._checked = false;
                this.props.excludeKeys.forEach(it=>{
                    delete item[it];
                })
            })
            data = data.concat(selectData);
            data = this.resetChecked(data)
            this.setState({
                data,
                copying:false,
                selectData:[]
            })
            let operObj = {
                operData:selectData,
                index:null,
                key:null,
                operType:"copyToEnd"
            }
            this.props.onChange(data,this.props.childType,operObj);
        }
    }
    //取消复制
    cancelCopy=()=>{
        let {cancelCopy,copyStatus} = this.props;
        if(copyStatus){
            cancelCopy();
        }else{
            this.setState({
                copying:false,
                selectData:[]
            })
        }
    }

    //最大化
    max=()=>{
        this.setState({
            isMax:!this.state.isMax
        })
    }
    //行hover
    onRowHover = (index,record) => {
        this.currentIndex = index;
    }

    //粘贴至此处按钮
    hoverContent=()=>{
        if(this.state.copying){
            return <span onClick={this.copyToHere} className='copy-to-here'>粘贴至此</span>
        }else{
            return ''
        }
    }
    //粘贴至此处
    copyToHere=()=>{
        let {childType} = this.props;
        let index = this.currentIndex;
        let data = cloneDeep(this.state.data);
        let selectData = this.state.selectData;
        selectData.forEach((item,i)=>{
            item._checked=false
            item.index = i+index+1;
            item.key = i+index+1+'';
        })
        data.splice(index,0,...selectData);
        data = this.resetChecked(data)
        this.setState({
            data,
            copying:false,
            selectData:[]
        })

        let operObj = {
            operData:selectData,
            index:index,
            key:null,
            operType:"copyToHere"
        }
        this.props.onChange(data,this.props.childType,operObj);
    }

    calcRenderData = (data) => {
        // let tempdata = cloneDeep(data);
        // tempdata && tempdata.map((item,index) => {
        //     if(item.persistStatus == "fdel") {
        //         data.splice(index,1)
        //     }
        // })
        data = data.filter(function(item) {
            return item.persistStatus !== "fdel"
        });
        return data;
    }

    renderDom=()=>{
        const { btnPageFlag,exportData, clsfix,title, data:propsData,columns:cl,disabled,fileEditFlag,hideBtns={}, ...otherProps } = this.props; 
        let { data,open,columns,copying,isMax } = this.state;
        let _exportData = exportData || data;
        let btnsObj = {};
        let tempdata = this.calcRenderData(data);

        if(isMax){
            btnsObj= {
                addRow:{
                    onClick:this.addRow,
                    disabled:disabled
                },
                delRow:{
                    onClick:this.delRow,
                    disabled:this.state.selectData==0||disabled
                },
                copyRow:{
                    onClick:this.copyRow,
                    disabled:this.state.selectData==0||disabled
                },
                extendToEnd:{
                    onClick:this.extendToEnd,
                    disabled:this.state.selectData.length!=1||disabled
                },
                copyToAssign:{
                    onClick:this.copyToAssign,
                    disabled:disabled
                },
                // min:{
                //     onClick:this.max
                // }
            }
        }else{
            if(!hideBtns.add) {
                btnsObj["addRow"] = {
                    onClick:this.addRow,
                    disabled:disabled
                };
            }
            if(!hideBtns.del) {
                btnsObj["delRow"] = {
                    onClick:this.delRow,
                    disabled:this.state.selectData==0||disabled
                };
            }
            if(!hideBtns.copy) {
                btnsObj["copyRow"] = {
                    onClick:this.copyRow,
                    disabled:this.state.selectData==0||disabled
                };
            }
            if(hideBtns.extendToEnd) {
                btnsObj["extendToEnd"] = {
                    onClick:this.extendToEnd,
                    disabled:this.state.selectData.length!=1||disabled
                };
            }
            if(hideBtns.copyToAssign) {
                btnsObj["copyToAssign"] = {
                    onClick:this.copyToAssign,
                    disabled:disabled
                };
                if(hideBtns.copyStatus){
                    btnsObj={
                        cancel:{
                            onClick:this.cancelCopy
                        },copyToEnd:{
                            onClick:this.copyToEnd
                        }
                    }
                }
            }
           
            // max:{
            //     onClick:this.max
            // }
            
        }
        if(copying && !hideBtns.copy){
            btnsObj={
                cancel:{
                    onClick:this.cancelCopy
                },copyToEnd:{
                    onClick:this.copyToEnd
                }
            }
        }

        if(btnPageFlag == "2") btnsObj={};

        return (
            <div className={`${clsfix} ${disabled?'disabled':''} ${isMax?'max':''}`}>
                <div className={`${clsfix}-panel ${open?'':'close'}`}>
                    {/* <span onClick={this.open}> */}
                        {/* <span className={`${clsfix}-panel-icon`}>
                            {
                                open?<Icon type='uf-triangle-down'/>:<Icon type='uf-triangle-right'/>
                            }
                        </span>
                        <span className={`${clsfix}-panel-title`}>
                            {title}
                        </span> */}
                    {/* </span> */}
                    {
                        open && !fileEditFlag?<span className={`${clsfix}-panel-btns`}>
                            {/* <ButtonGroup> */}
                                <Btns btns={btnsObj}
                                    addToBtns={
                                        {
                                            'extendToEnd':{ 
                                                'colors':'write',
                                                'name_zh_CN':'填充至指定行',
                                                'className':'ac-btns-extendToEnd'
                                            },
                                            'copyToAssign':{ 
                                                'colors':'write',
                                                'name_zh_CN':'复制指定行',
                                                'className':'ac-btns-extendToEnd'
                                            }
                                        }
                                    }
                                />
                            {/* </ButtonGroup> */}
                        </span>:''
                    }
                    
                </div>
                <div className={`${clsfix}-inner ${open?'show':'hide'} ${isMax?'max':''}`}>
                            <AcGird
                                {...otherProps}
                                noReplaceColumns={true}
                                columns = {columns}
                                data={tempdata}
                                exportData={_exportData}
                                // paginationObj={paginationObj}
                                getSelectedDataFunc={this.getSelectedDataFunc}
                                hoverContent={this.hoverContent}
                                onRowHover={this.onRowHover}
                                autoCheckedByClickRows = {false}
                            />
                        </div>
            </div>
        )
        
    }

    render() {
        return (
            <span>
                {
                    this.state.isMax?ReactDOM.createPortal(this.renderDom(),document.querySelector('body')):this.renderDom()
                }
            </span>
        )
        
    }
}

EditGrid.defaultProps = defaultProps;
EditGrid.propTypes = propTypes;
export default EditGrid;
